package executor.service.jobhandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import executor.Entity.*;
import executor.dao.TestdataDao;
import freemarker.template.*;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Statement;
import java.util.*;

@Component
public class BeanXxlJob {
    private static Logger logger = LoggerFactory.getLogger(BeanXxlJob.class);

    @Autowired
    private TestdataDao testdataDao;

    private Configuration configuration;

    protected static Statement statement = null;
    protected static String insertTable = "Testdata";

    public static BeanXxlJob beanXxlJob;

    private static org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(BeanXxlJob.class);
    private static final String ENCODING = "UTF-8";
    private static Configuration cfg = new Configuration();

    //初始化cfg
    static {
        //设置模板所在文件夹
        cfg.setClassForTemplateLoading(BeanXxlJob.class,"/demo/word");
        // setEncoding这个方法一定要设置国家及其编码，不然在ftl中的中文生成html后会乱码
        cfg.setEncoding(Locale.getDefault(),ENCODING);
        //设置对象包装器
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        // 设置异常处理器，这样的话就可以${a}没有报错
        cfg.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
    }

    //获取模板对象
    public static Template getTemplate(String templateFileName) throws IOException {
        return cfg.getTemplate(templateFileName,ENCODING);
    }
    /**
     * 数据及模板生成文件
     * @param data Map的数据结果集
     * @param templateFileName ftl模板文件名
     * @param outFilePath 生成文件名称
     */

    public static File crateFile(Map<String,Object>data,String templateFileName , String outFilePath){
        Writer out = null;
        File outFile = new File(outFilePath);
        try {
            //获取模板，并设置编码方式，这个编码必须要与界面中的编码格式一致
            Template template = getTemplate(templateFileName);
            if (!outFile.getParentFile().exists()){
                outFile.getParentFile().mkdirs();
            }
            out = new OutputStreamWriter(new FileOutputStream(outFile),ENCODING);
            //处理模板
            template.process(data,out);
            out.flush();
            log.info("由模板文件" + templateFileName + "生成" + outFilePath + "成功.");
        }catch (Exception e){
            log.error("由模板文件" + templateFileName + "生成" + outFilePath + "出错.");
            e.printStackTrace();
        }finally {
            try {
                if (out !=null){
                    out.close();
                }
            }catch (IOException e){
                log.error("关闭Write对象出错",e);
                e.printStackTrace();
            }

        }

        return outFile;
    }


    //定时执行器
    @XxlJob("BeanJobHandler")//JobHandler
    public ReturnT<String>BeanJobHandler(String param) throws Exception{
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();



        //创建Post请求
        //参数
        URI uri = null;

        try {

            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("flag", "4"));
            params.add(new BasicNameValuePair("meaning", "1"));
            //Token值
            String token = "db32a74e4d6593cb17bc9ec81d82ee6f4e3bf090b8d2db34e92f16b5e7d82f9a";
            //API路径
            uri = new URIBuilder().setScheme("https").setHost("tower.im/api/v1").setPath("/user").setParameters(params).build();
        }catch (URISyntaxException e1){
            e1.printStackTrace();
        }
        //请求头
        HttpGet httpGet = new HttpGet(uri);
        httpGet.addHeader("Content-type","application/json;charset=utf8");
        httpGet.addHeader("Host","<calculated when request is sent>");
        httpGet.addHeader("Authorization","Bearer 0797eeae86d2346aa58546be9d171ee6b8bc560e543e735d02c519b70f348268");
        httpGet.addHeader("Cookie","uid=rBACIl7DTBnAfRKgWiALAg==; _ga=GA1.2.567674898.1589857720; intercom-id-xbtsuf77=e783b7c4-de5e-494b-a6c9-f45d78baac5e; mp_72ddb7dd79e1c48afb3e27e0efd70a74_mixpanel=%7B%22distinct_id%22%3A%20%221722ae795434d9-037e3d871b94f3-26096c2f-144000-1722ae7954448e%22%2C%22%24device_id%22%3A%20%221722ae795434d9-037e3d871b94f3-26096c2f-144000-1722ae7954448e%22%2C%22%24initial_referrer%22%3A%20%22%24direct%22%2C%22%24initial_referring_domain%22%3A%20%22%24direct%22%7D; remember_token=63009470-4880-4bb8-adfe-0581ca97fac7; remember_team_guid=66f9f25eee0a44d18282ffdcd0b33e1f; _tower2_session=1b9090567d7db90a5ba900dfeba4d606; Hm_lvt_e1fa918d304786452f7d6936febd93c6=1589966127,1590134154,1590197438,1590732580; Hm_lpvt_e1fa918d304786452f7d6936febd93c6=1590732580; _gid=GA1.2.994055032.1590732580");

        //响应模型
        CloseableHttpResponse response = null;
        try {
            //由客户端执行（发送）Get请求
            response = httpClient.execute(httpGet);
            //从响应模型中获取响应实体并存入数据库
            HttpEntity responseEntity = response.getEntity();
            final String dataOne = EntityUtils.toString(responseEntity);
            Testdata testdata = new Testdata();
            testdata.setResultData(dataOne);
            testdata.setCreateTime(new Date());
            int insert = testdataDao.insert(testdata);
            if (responseEntity!=null){
                System.out.println("======响应内容长度为:"+responseEntity.getContentLength());
                System.out.println("======响应内容为:"+ dataOne);
                System.out.println("以下数据已存入数据库并发送到钉钉群:"+dataOne);
            }
            //钉钉机器人
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/robot/send?access_token=6d1062a503a1e3c53a2ae24a3d0e874e3483d10b7791ff3aff651f9899499a06");
            OapiRobotSendRequest request = new OapiRobotSendRequest();
            request.setMsgtype("text");
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            text.setContent("安全报警:"+dataOne);
            request.setText(text);

            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            //设置@所有的人
//            at.setIsAtAll("true");
            request.setAt(at);
            OapiRobotSendResponse msg = client.execute(request);
            System.out.println(msg.getErrcode());
            System.out.println(msg.getErrmsg());

            //解析JSON数据
            String List = dataOne;
            JSONObject dataList = JSON.parseObject(List);
            Object data = dataList.get("data");
            JSONObject jsonObject = (JSONObject) JSON.parseObject(String.valueOf(data));

            Object attributes = jsonObject.get("attributes");
            //JsonDataVO数据
            JsonDataVO jsonDataVO = JSON.parseObject(String.valueOf(data), JsonDataVO.class);
            //AttributesVO数据
            AttributesVO attributesVO = JSON.parseObject(String.valueOf(attributes), AttributesVO.class);
            //Id数据
            Id id = JSON.parseObject(String.valueOf(data),Id.class);
            //Email数据
            Email email = JSON.parseObject(String.valueOf(attributes),Email.class);

            //数据放入Word文档
            Map<String,Object> data2 = new HashMap<String, Object>();
            data2.put("test1",jsonDataVO);
            data2.put("test2",attributesVO);
            data2.put("test3",id);
            data2.put("test4",email);
            data2.put("test5","测试5");
            data2.put("test6","测试6");
            data2.put("test7","测试7");
            List<Map<String,String>> educations = new ArrayList<Map<String, String>>();
            crateFile(data2,"demo2.ftl","C:/Users/12561/Desktop/demoTest.doc");
            System.out.println("添加成功");
        }catch (ClientProtocolException e){
            e.printStackTrace();
        }catch (ParseException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            try {
                //释放资源
                if (httpClient!=null){
                    httpClient.close();
                }
                if (response!=null){
                    response.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        System.out.println("以上为测试数据，Token刷新时间为两小时。");
        return ReturnT.SUCCESS;
    }

    public  void save(String data){

    }

    }

